library(readstata13)
library(ggplot2)
library(rgdal)
library(sp)
library(tmap)

rm(list=ls()) # Clean enviroment

# ---- Define folders and relevant values ---- #

## Detect system and define main folder accordingly:
user <- Sys.info()[["user"]]
OSsystem <- .Platform$OS.type

## main data folder
if (user == "David") {
  main_folder <- paste0("C:/Users/",user,"/Dropbox/Research/UR/Juan+Mounu/Coca/Paper Replication")
} else {
  main_folder <- paste("/Users/",user,"/Dropbox/Coca/Paper Replication", sep = "")
  if( .Platform$OS.type == "windows" )
    main_folder <- paste("C:/Users/",user,"/Dropbox/Coca/Paper Replication", sep = "")
}

## Data folder
data_folder <- paste(main_folder,"/Data", sep = "")

## Raw shape municipalities
shape_folder <- paste(data_folder,"/_aux/Municipios_shape", sep="")

## output folder
output_folder <- paste(main_folder,"/Figures", sep = "")

########################### map ###########################

# Get Map
base <- readOGR(shape_folder, 'MunicipiosNew')

# get data
data <- paste0(data_folder, "/data_for_maps.dta")
coca_data <- readstata13::read.dta13(data)

# prepare data
base$muni_code <- as.numeric(as.character(base$MPIO_CCDGO))
final <- sp::merge(base, coca_data, by = "muni_code")

# ----------- plots ------------

### Suitability
pdf(file = paste0(output_folder, "/sutability_map.pdf"))

legend_title = expression("Coca Difference")
tm_shape(final) + tm_polygons(col = "diff_coca_area_cat",  palette = "Greys" , title = legend_title, style = "pretty", n = 5, contrast = c(0.52, 1)) + tm_symbols(col = "black", border.col = "white", style = "quantile", n = 5, size = "suitability") +
  tm_legend(show=FALSE) + tm_layout(frame = FALSE) 

dev.off()

### PNIS probablity 
pdf(file = paste0(output_folder, "/prPNIS_map.pdf"))

legend_title = expression("Coca Difference")
tm_shape(final) + tm_polygons(col = "diff_coca_area_cat",  palette = "Greys" , title = legend_title, style = "pretty", n = 5, contrast = c(0.52, 1)) + tm_symbols(col = "black", border.col = "white", style = "quantile", n = 5, size = "pr_PNIS") +
  tm_legend(show=FALSE) + tm_layout(frame = FALSE) 

dev.off()
